# -*- coding: utf-8 -*-
from socket import *


# params: connectIp:服务器IP, connectPort:服务器端口

class TcpServer():
    def __init__(self, connectPort=8001,connectIP=None):
        self.tcp_server = None
        self.connectPort = connectPort
        self.connectIP = connectIP

    # 创建tcp连接服务器
    def createServer(self):
        try:
            tcp_server = socket(AF_INET, SOCK_STREAM)
            address = ('', self.connectPort)
            tcp_server.bind(address)
            tcp_server.listen(5)
            self.tcp_server = tcp_server
        except Exception as e:
            print(e)
            return None

    # 接收客户端消息
    def receiveMsg(self):
        try:
            client_socket, clientAddr = self.tcp_server.accept()
            from_client_msg = client_socket.recv(1024)
            self.tcp_server.close()
            if from_client_msg.decode("utf-8"):
                return True
            else:
                return False
        except Exception as e:
            print(e)

    # 创建tcp服务器并接收消息
    def receive(self):
        try:
            self.createServer()
            return self.receiveMsg()
        except Exception as e:
            print(e)

#
# if __name__ == '__main__':
#     tcpServer = TcpServer('192.168.61.187', 8001)
#     res = tcpServer.receive()
#     print(res)
